<template>
  <div ref="wrapper" style="display: inline-flex;" @mouseover="emitWidth">
    <el-button
        v-for="button in $buttons"
        v-bind="{...button}"
        @click.prevent="handleClick(button, $event)"
    >
      <strong v-html="button.title"></strong>
    </el-button>
  </div>
</template>

<script setup lang="ts">

import {computed, onMounted, ref} from "vue";
import _ from 'lodash'
import type {MTableButton} from "../../types/table/m.table.types";

const emits = defineEmits(['click', 'width'])
const props = defineProps<{
  buttons: MTableButton[],
  item: any
}>()
const wrapper = ref()


const $buttons = computed(() => props.buttons.map(convert))

function convert(button: MTableButton) {
  const btn = _.mapValues(button, (v, k) => k === 'handler' ? v : v instanceof Function ? v(props.item) : v)
  btn.size = btn.size || 'small'
  btn.type = btn.type || 'primary'
  btn.link = btn.link || true
  btn.disabled = btn.disabled || !btn.handler
  return btn
}

onMounted(emitWidth)

function emitWidth() {
  emits('width', parseFloat(wrapper.value.offsetWidth))
}

function handleClick(button: MTableButton, event: Event) {
  const handler = button.handler
  handler && handler(props.item, event)
}

</script>

<style scoped>

</style>